package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author XiaoLuo
 * @ClassName: UploadServiceImpl
 * @Description: ${todo}
 * @date 2019/4/15 20:42
 */

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

/*	private static final Logger LOGGER=
			LoggerFactory.getLogger(UploadServiceImpl.class);*/

	//支持文件的类型
	private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

	@Autowired FastFileStorageClient storageClient;


	@Override public String upload(MultipartFile file) {
		//1.图片信息校验
		//1)校验图片类型
		try {
			String type = file.getContentType();
			if(!suffixes.contains(type)){
				log.info("上传失败，文件类型不匹配: {}",type);
				return null;
			}
			//2）校验图片内容
			BufferedImage image = ImageIO.read(file.getInputStream());
			if(image==null){
				log.info("上传失败，文件内容不符合要求");
				return null;
			}
			//2将图片上传到FastDFS
			//1)先获取文件名，然后获取文件后缀
			String originalFilename = file.getOriginalFilename();
			//以最后一个点开始截取最后的字符串
			String extension = StringUtils
					.substringAfterLast(originalFilename, ".");
			//2)上传
			//参数：输入流  文件大小  文件后缀
			StorePath storePath = this.storageClient
					.uploadFile(file.getInputStream(), file.getSize(),
							extension, null);

			//3)拼接图片地址a
			String url = "http://image.leyou.com/" + storePath.getFullPath();
			return url;
		} catch (Exception e) {
			return null;
		}

	}
}
